'use client'

import { useState, useEffect } from 'react'
import { User, Mail, Phone, MapPin, Camera, Save, X, Plus, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { useToast } from '@/hooks/use-toast'
import { authAPI } from '@/lib/api'
import { getAvatarUrl } from '@/lib/utils'
import { CompactLayout, CompactCard, CompactGrid, CompactHeading, CompactSubheading } from '@/components/ui/compact-layout'
import { ToastContainer } from '@/components/ui/toast'
import type { UserProfile, ProfileUpdateData } from '@/lib/types'

// 预设部门列表
const DEPARTMENTS = [
  '技术部',
  '产品部',
  '设计部',
  '运营部',
  '市场部',
  '销售部',
  '人事部',
  '财务部',
  '法务部',
  '其他'
]

export default function ProfilePage() {
  const { toast, dismiss, toasts } = useToast()
  const [isEditing, setIsEditing] = useState(false)
  const [isSaving, setIsSaving] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [avatarFile, setAvatarFile] = useState<File | null>(null)
  const [avatarPreview, setAvatarPreview] = useState<string>('')

  // 用户资料数据
  const [userData, setUserData] = useState<UserProfile>({
    id: '',
    username: '',
    email: '',
    role: 'VIEWER',
    avatar: '',
    status: 'ACTIVE',
    lastLoginAt: '',
    createdAt: '',
    updatedAt: '',
    fullName: '',
    phone: '',
    department: '',
    position: '',
    bio: '',
    location: '',
    website: '',
    skills: []
  })

  // 技能标签编辑状态
  const [editingSkill, setEditingSkill] = useState<string>('')
  const [newSkill, setNewSkill] = useState<string>('')

  // 加载用户资料
  useEffect(() => {
    loadUserProfile()
  }, [])

  const loadUserProfile = async () => {
    try {
      setIsLoading(true)
      const user = await authAPI.getCurrentUser()
      
      // 设置用户数据，使用后端返回的数据或默认值
      const profileData: UserProfile = {
        ...user,
        fullName: user.fullName || user.username,
        phone: user.phone || '',
        department: user.department || '未设置',
        position: user.position || '未设置',
        bio: user.bio || '这个人很懒，还没有写个人简介...',
        location: user.location || '未设置',
        website: user.website || '',
        skills: user.skills || []
      }
      
             setUserData(profileData)
       // 设置头像预览，只有当有头像时才设置
       const avatarUrl = getAvatarUrl(user.avatar)
       if (avatarUrl) {
         setAvatarPreview(avatarUrl)
       } else {
         setAvatarPreview('')
       }
    } catch (error) {
      console.error('加载用户资料失败:', error)
      toast({
        title: '加载失败',
        description: '无法加载用户资料，请稍后重试',
        variant: 'destructive'
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setAvatarFile(file)
      const reader = new FileReader()
      reader.onload = (e) => {
        setAvatarPreview(e.target?.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  // 技能标签编辑处理函数
  const handleAddSkill = () => {
    if (newSkill.trim() && !userData.skills?.includes(newSkill.trim())) {
      setUserData(prev => ({
        ...prev,
        skills: [...(prev.skills || []), newSkill.trim()]
      }))
      setNewSkill('')
    }
  }

  const handleRemoveSkill = (skillToRemove: string) => {
    setUserData(prev => ({
      ...prev,
      skills: prev.skills?.filter(skill => skill !== skillToRemove) || []
    }))
  }

  const handleEditSkill = (oldSkill: string, newSkillValue: string) => {
    if (newSkillValue.trim() && newSkillValue !== oldSkill) {
      setUserData(prev => ({
        ...prev,
        skills: prev.skills?.map(skill => 
          skill === oldSkill ? newSkillValue.trim() : skill
        ) || []
      }))
    }
    setEditingSkill('')
  }

  const handleSave = async () => {
    try {
      setIsSaving(true)
      
             // 更新头像
       if (avatarFile) {
         const avatarResult = await authAPI.updateAvatar(avatarFile)
         // 更新用户数据和头像预览，使用getAvatarUrl处理路径
         const avatarUrl = getAvatarUrl(avatarResult.avatar)
         setUserData(prev => ({ ...prev, avatar: avatarResult.avatar }))
         if (avatarUrl) {
           setAvatarPreview(avatarUrl)
         } else {
           setAvatarPreview('')
         }
         setAvatarFile(null)
       }
      
      // 更新用户资料
      const updateData: ProfileUpdateData = {
        fullName: userData.fullName,
        phone: userData.phone,
        department: userData.department,
        position: userData.position,
        bio: userData.bio,
        location: userData.location,
        website: userData.website || undefined, // 如果为空字符串则设为 undefined
        skills: userData.skills
      }
      
      // 调用更新接口
      const updatedUser = await authAPI.updateProfile(updateData)
      setUserData(prev => ({ ...prev, ...updatedUser }))
      
      toast({
        title: '保存成功',
        description: '用户资料已成功更新',
      })
      
      setIsEditing(false)
    } catch (error) {
      console.error('保存失败:', error)
      toast({
        title: '保存失败',
        description: '更新用户资料时出现错误，请稍后重试',
        variant: 'destructive'
      })
    } finally {
      setIsSaving(false)
    }
  }

  const handleCancel = () => {
    setIsEditing(false)
    setAvatarFile(null)
    setEditingSkill('')
    setNewSkill('')
    // 重新加载用户资料，恢复原始数据
    loadUserProfile()
  }

  const getRoleBadgeColor = (role: string) => {
    switch (role) {
      case 'ADMIN':
        return 'bg-red-100 text-red-800'
      case 'EDITOR':
        return 'bg-blue-100 text-blue-800'
      case 'VIEWER':
        return 'bg-gray-100 text-gray-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  const getRoleLabel = (role: string) => {
    switch (role) {
      case 'ADMIN':
        return '管理员'
      case 'EDITOR':
        return '编辑者'
      case 'VIEWER':
        return '查看者'
      default:
        return '未知'
    }
  }

  const formatDate = (dateString: string) => {
    if (!dateString) return '未知'
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  }

  if (isLoading) {
    return (
      <CompactLayout>
        <div className="flex items-center justify-center h-64">
          <Loader2 className="h-8 w-8 animate-spin" />
          <span className="ml-2">加载中...</span>
        </div>
      </CompactLayout>
    )
  }

  return (
    <>
      <CompactLayout>
        {/* 页面标题 */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <CompactHeading>个人资料</CompactHeading>
            <CompactSubheading>管理您的个人信息和账户设置</CompactSubheading>
          </div>
          <div className="flex space-x-2">
            {!isEditing ? (
              <Button onClick={() => setIsEditing(true)} size="sm" className="h-8">
                <User className="mr-2 h-4 w-4" />
                编辑资料
              </Button>
            ) : (
              <>
                <Button variant="outline" onClick={handleCancel} size="sm" className="h-8">
                  <X className="mr-2 h-4 w-4" />
                  取消
                </Button>
                <Button onClick={handleSave} disabled={isSaving} size="sm" className="h-8">
                  <Save className="mr-2 h-4 w-4" />
                  {isSaving ? '保存中...' : '保存'}
                </Button>
              </>
            )}
          </div>
        </div>

        <CompactGrid cols={3} className="gap-4">
          {/* 左侧：头像和基本信息 */}
          <div className="space-y-4">
            {/* 头像卡片 */}
            <CompactCard>
              <div className="p-3">
                <h3 className="text-lg font-semibold mb-3">头像</h3>
                <div className="text-center space-y-3">
                  <div className="relative inline-block">
                    <Avatar className="h-20 w-20">
                      {(avatarPreview || getAvatarUrl(userData.avatar)) ? (
                        <AvatarImage 
                          src={avatarPreview || getAvatarUrl(userData.avatar)} 
                          alt={userData.fullName || userData.username} 
                        />
                      ) : null}
                      <AvatarFallback className="text-xl">
                        {(userData.fullName || userData.username).charAt(0)}
                      </AvatarFallback>
                    </Avatar>
                    {isEditing && (
                      <label className="absolute bottom-0 right-0 bg-primary text-primary-foreground rounded-full p-1.5 cursor-pointer hover:bg-primary/90">
                        <Camera className="h-3 w-3" />
                        <input
                          type="file"
                          className="hidden"
                          accept="image/*"
                          onChange={handleAvatarChange}
                        />
                      </label>
                    )}
                  </div>
                  {isEditing && (
                    <div className="text-xs text-muted-foreground">
                      点击相机图标更换头像
                    </div>
                  )}
                </div>
              </div>
            </CompactCard>

            {/* 账户信息卡片 */}
            <CompactCard>
              <div className="p-3">
                <h3 className="text-lg font-semibold mb-3">账户信息</h3>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">用户名</span>
                    <span className="text-sm font-medium">{userData.username}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">角色</span>
                    <Badge className={`text-xs ${getRoleBadgeColor(userData.role)}`}>
                      {getRoleLabel(userData.role)}
                    </Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">部门</span>
                    <span className="text-sm font-medium">{userData.department}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">职位</span>
                    <span className="text-sm font-medium">{userData.position}</span>
                  </div>
                  <Separator />
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">注册时间</span>
                    <span className="text-xs">{formatDate(userData.createdAt)}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">最后登录</span>
                    <span className="text-xs">{userData.lastLoginAt ? formatDate(userData.lastLoginAt) : '从未登录'}</span>
                  </div>
                </div>
              </div>
            </CompactCard>
          </div>

          {/* 右侧：详细信息 */}
          <div className="col-span-2 space-y-4">
            {/* 基本信息 */}
            <CompactCard>
              <div className="p-3">
                <h3 className="text-lg font-semibold mb-3">基本信息</h3>
                <div className="space-y-3">
                  <div className="grid gap-3 md:grid-cols-2">
                    <div>
                      <label className="text-xs font-medium">姓名</label>
                      {isEditing ? (
                        <Input
                          value={userData.fullName || ''}
                          onChange={(e) => setUserData({...userData, fullName: e.target.value})}
                          className="mt-1 h-8 text-sm"
                        />
                      ) : (
                        <div className="mt-1 p-2 bg-muted rounded-md text-sm">
                          {userData.fullName || '未设置'}
                        </div>
                      )}
                    </div>
                    <div>
                      <label className="text-xs font-medium">邮箱</label>
                      {isEditing ? (
                        <Input
                          type="email"
                          value={userData.email}
                          onChange={(e) => setUserData({...userData, email: e.target.value})}
                          className="mt-1 h-8 text-sm"
                        />
                      ) : (
                        <div className="mt-1 p-2 bg-muted rounded-md flex items-center text-sm">
                          <Mail className="mr-2 h-3 w-3 text-muted-foreground" />
                          {userData.email}
                        </div>
                      )}
                    </div>
                  </div>
                  <div className="grid gap-3 md:grid-cols-2">
                    <div>
                      <label className="text-xs font-medium">手机号码</label>
                      {isEditing ? (
                        <Input
                          value={userData.phone || ''}
                          onChange={(e) => setUserData({...userData, phone: e.target.value})}
                          className="mt-1 h-8 text-sm"
                        />
                      ) : (
                        <div className="mt-1 p-2 bg-muted rounded-md flex items-center text-sm">
                          <Phone className="mr-2 h-3 w-3 text-muted-foreground" />
                          {userData.phone || '未设置'}
                        </div>
                      )}
                    </div>
                    <div>
                      <label className="text-xs font-medium">所在地区</label>
                      {isEditing ? (
                        <Input
                          value={userData.location || ''}
                          onChange={(e) => setUserData({...userData, location: e.target.value})}
                          className="mt-1 h-8 text-sm"
                        />
                      ) : (
                        <div className="mt-1 p-2 bg-muted rounded-md flex items-center text-sm">
                          <MapPin className="mr-2 h-3 w-3 text-muted-foreground" />
                          {userData.location || '未设置'}
                        </div>
                      )}
                    </div>
                  </div>
                  <div className="grid gap-3 md:grid-cols-2">
                    <div>
                      <label className="text-xs font-medium">部门</label>
                      {isEditing ? (
                        <select
                          value={userData.department || ''}
                          onChange={(e) => setUserData({...userData, department: e.target.value})}
                          className="mt-1 h-8 text-sm w-full px-2 py-1 border border-input rounded-md bg-background"
                        >
                          <option value="">请选择部门</option>
                          {DEPARTMENTS.map(dept => (
                            <option key={dept} value={dept}>{dept}</option>
                          ))}
                        </select>
                      ) : (
                        <div className="mt-1 p-2 bg-muted rounded-md text-sm">
                          {userData.department || '未设置'}
                        </div>
                      )}
                    </div>
                    <div>
                      <label className="text-xs font-medium">职位</label>
                      {isEditing ? (
                        <Input
                          value={userData.position || ''}
                          onChange={(e) => setUserData({...userData, position: e.target.value})}
                          className="mt-1 h-8 text-sm"
                          placeholder="如：前端工程师"
                        />
                      ) : (
                        <div className="mt-1 p-2 bg-muted rounded-md text-sm">
                          {userData.position || '未设置'}
                        </div>
                      )}
                    </div>
                  </div>
                  <div>
                    <label className="text-xs font-medium">个人网站</label>
                    {isEditing ? (
                      <Input
                        value={userData.website || ''}
                        onChange={(e) => setUserData({...userData, website: e.target.value})}
                        className="mt-1 h-8 text-sm"
                        placeholder="https://example.com"
                      />
                    ) : (
                      <div className="mt-1 p-2 bg-muted rounded-md text-sm">
                        {userData.website || '未设置'}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </CompactCard>

            {/* 个人简介 */}
            <CompactCard>
              <div className="p-3">
                <h3 className="text-lg font-semibold mb-3">个人简介</h3>
                {isEditing ? (
                  <Textarea
                    value={userData.bio || ''}
                    onChange={(e) => setUserData({...userData, bio: e.target.value})}
                    placeholder="介绍一下自己..."
                    rows={3}
                    className="text-sm"
                  />
                ) : (
                  <div className="p-2 bg-muted rounded-md text-sm">
                    {userData.bio || '暂无个人简介'}
                  </div>
                )}
              </div>
            </CompactCard>

            {/* 技能标签 */}
            <CompactCard>
              <div className="p-3">
                <h3 className="text-lg font-semibold mb-3">技能标签</h3>
                <div className="space-y-3">
                  {/* 技能标签列表 */}
                  <div className="flex flex-wrap gap-2">
                    {userData.skills?.map((skill, index) => (
                      <div key={index} className="flex items-center gap-1">
                        {editingSkill === skill ? (
                          <div className="flex items-center gap-1">
                            <Input
                              value={editingSkill}
                              onChange={(e) => setEditingSkill(e.target.value)}
                              className="h-6 w-20 text-xs"
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                  handleEditSkill(skill, editingSkill)
                                } else if (e.key === 'Escape') {
                                  setEditingSkill('')
                                }
                              }}
                              autoFocus
                            />
                            <Button
                              variant="outline"
                              size="sm"
                              className="h-6 w-6 p-0"
                              onClick={() => handleEditSkill(skill, editingSkill)}
                            >
                              ✓
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              className="h-6 w-6 p-0"
                              onClick={() => setEditingSkill('')}
                            >
                              ✕
                            </Button>
                          </div>
                        ) : (
                          <Badge variant="secondary" className="text-xs">
                            {skill}
                          </Badge>
                        )}
                        {isEditing && editingSkill !== skill && (
                          <div className="flex items-center gap-1 ml-1">
                            <Button
                              variant="outline"
                              size="sm"
                              className="h-5 w-5 p-0 text-xs"
                              onClick={() => setEditingSkill(skill)}
                            >
                              ✎
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              className="h-5 w-5 p-0 text-xs"
                              onClick={() => handleRemoveSkill(skill)}
                            >
                              ×
                            </Button>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                  
                  {/* 添加新技能 */}
                  {isEditing && (
                    <div className="flex items-center gap-2">
                      <Input
                        value={newSkill}
                        onChange={(e) => setNewSkill(e.target.value)}
                        placeholder="输入新技能"
                        className="h-8 text-sm"
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') {
                            handleAddSkill()
                          }
                        }}
                      />
                      <Button
                        variant="outline"
                        size="sm"
                        className="h-8"
                        onClick={handleAddSkill}
                        disabled={!newSkill.trim()}
                      >
                        <Plus className="mr-1 h-3 w-3" />
                        添加
                      </Button>
                    </div>
                  )}
                </div>
              </div>
            </CompactCard>
          </div>
        </CompactGrid>
      </CompactLayout>
      
      {/* Toast 通知 */}
      <ToastContainer toasts={toasts} onDismiss={dismiss} />
    </>
  )
}
